package cn.jxau.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.jxau.auth.annotation.AccessIllegalException;
import cn.jxau.auth.annotation.PrivilegeAnnotation;
import cn.jxau.bean.po.User;
import cn.jxau.bean.vo.JsonResult;
import cn.jxau.common.util.JacksonUtils;


/**
 * 全局拦截器，进行一个全局消息的写入,该拦截器将会拦截所有的请求，并对请求进行分析，看处理器方法上
 * 是否添加有@PrivilegeAnnotation注解，如果有，将会对其相应的权限进行验证
 * @author licho
 *
 */
public class GlobalMessageInterceptor implements HandlerInterceptor {
	private static Logger log=Logger.getLogger(GlobalMessageInterceptor.class);
	/**
	 * 前置处理器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String serverIP=InetAddress.getLocalHost().getHostAddress();
		boolean flag=true;
		// TODO Auto-generated method stub
		String base=request.getContextPath();
		request.setAttribute("_root", base);//将contextPath替换为_root
		request.setAttribute("_ip", serverIP+":8080");
		try{
			this.validateAccess(request, response, handler);
		}catch(AccessIllegalException e){
			boolean isResp=request.getParameter("_login")==null ? false :true;
			if(isResp){
				//需要响应
				printJsonMessage(response, getAccessJson());
			}else{
				response.sendRedirect(base+"/jsp/login");
			}
			log.debug("权限不通过");
			flag=false;
		}
		return flag;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	

	
	/** 
	 * 对该资源的用户角色相关权限进行检查
	 * @param request	请求
	 * @param response 响应
	 * @param handler 对应的处理器
	 * @throws AccessIllegalException
	 */
	public void validateAccess(HttpServletRequest request,HttpServletResponse response,Object handler)throws AccessIllegalException{
		if(!(handler instanceof HandlerMethod)){//如果是默认处理器
			return;
		}
		PrivilegeAnnotation auth=((HandlerMethod)handler).getMethodAnnotation(PrivilegeAnnotation.class);
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("user");//尝试获取用户信息
		if(auth==null)//不必进行权限控制
			return;
		Long roleID=auth.value().getRoleID();//希望用户拥有的角色
		log.debug("希望用户拥有角色:"+auth.value().getRoleName());
		if((roleID!=0L)&&user==null)
			throw new AccessIllegalException();//抛出异常
		log.debug("用户的角色是："+user.getRoleID()+"(1超级管理员,2管理员,3普通用户)");
		if(roleID==1L){
			//具有登录权限
			if(!(user.getRoleID()>=1L)){//
				
				throw new AccessIllegalException();//抛出异常
			}
		}else if(roleID==2L){
			//具有管理员权限
			if(!(user.getRoleID()<=2L)){
				throw new AccessIllegalException();
			}
		}else if(roleID==3L){
			//具有超级管理员权限
			if(!user.getRoleID().equals(1L)){
				throw new AccessIllegalException();
			}
		}
		
	}
	
	/**
	 * 对于某些ajax请求拦截的页面的要求进行回应的页面，通过403错误告知其请求权限不够
	 * @return
	 */
	private String getAccessJson(){
		JsonResult result=new JsonResult();
		result.setMsg("权限不足");
		result.setStatus("403");//权限不足
		return JacksonUtils.converToJson(result);
	}
	
	private void printJsonMessage(HttpServletResponse resp,String msg){
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json;charset=utf-8");
		try {
			PrintWriter writer=resp.getWriter();
			writer.write(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}

